<template>
  <div class="card-type-list">
    <el-card class="card-type-card">
      <template #header>
        <div class="card-header">
          <span>会员卡类型列表</span>
          <el-button type="primary" @click="handleAdd">添加卡类型</el-button>
        </div>
      </template>

      <el-table
        :data="cardTypeList"
        v-loading="loading"
        style="width: 100%"
        row-key="id"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="类型名称" show-overflow-tooltip />
        <el-table-column prop="price" label="价格(元)" width="100" />
        <el-table-column prop="validityPeriod" label="有效期(天)" width="120" />
        <el-table-column prop="discount" label="折扣率" width="100">
          <template #default="scope">
            {{ (scope.row.discount * 10).toFixed(1) }}折
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row)"
              :disabled="scope.row.status === 0"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑卡类型对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      @close="handleDialogClose"
    >
      <el-form
        ref="cardTypeFormRef"
        :model="cardTypeForm"
        :rules="cardTypeRules"
        label-width="100px"
      >
        <el-form-item label="卡类型名称" prop="name">
          <el-input v-model="cardTypeForm.name" :maxlength="50" show-word-limit />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="cardTypeForm.description" type="textarea" :maxlength="200" show-word-limit />
        </el-form-item>
        <el-form-item label="价格(元)" prop="price">
          <el-input-number
            v-model="cardTypeForm.price"
            :min="0"
            :step="100"
            controls-position="right"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="有效期(天)" prop="validityPeriod">
          <el-input-number
            v-model="cardTypeForm.validityPeriod"
            :min="1"
            :max="3650"
            controls-position="right"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="折扣率" prop="discount">
          <el-slider
            v-model="cardTypeForm.discount"
            :min="0"
            :max="1"
            :step="0.05"
            show-input
            :format-tooltip="formatDiscount"
          />
        </el-form-item>
        <el-form-item v-if="isEdit" label="状态" prop="status">
          <el-switch
            v-model="cardTypeForm.status"
            :active-value="1"
            :inactive-value="0"
            active-text="正常"
            inactive-text="禁用"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave" :loading="saveLoading">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type {
  CardType,
  CreateCardTypeRequest,
  UpdateCardTypeRequest
} from '@/types/api/card'
import { cardApi } from '@/api/modules/card'
import { preventDuplicateSubmit, formUtils } from '@/utils'

// 表格相关
const loading = ref(false)
const cardTypeList = ref<CardType[]>([])

// 分页相关
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)
const saveLoading = ref(false)
const cardTypeFormRef = ref()
const currentCardTypeId = ref(0)

// 表单数据
const cardTypeForm = reactive({
  name: '',
  description: '',
  price: 0,
  validityPeriod: 365,
  discount: 1,
  status: 1
})

// 表单验证规则
const cardTypeRules = {
  name: [
    { required: true, message: '请输入类型名称', trigger: 'blur' }
  ],
  price: [
    { required: true, message: '请输入价格', trigger: 'blur' }
  ],
  validityPeriod: [
    { required: true, message: '请输入有效期', trigger: 'blur' }
  ],
  discount: [
    { required: true, message: '请选择折扣率', trigger: 'change' }
  ]
}

// 格式化折扣率显示
const formatDiscount = (value: number) => {
  return `${(value * 10).toFixed(1)}折`
}

// 获取会员卡类型列表
const getCardTypeList = async () => {
  loading.value = true
  try {
    const response = await cardApi.getCardTypeList({
      page: pagination.page,
      pageSize: pagination.pageSize
    })
    cardTypeList.value = response.data.data.list
    pagination.total = response.data.data.total
  } catch (error) {
    ElMessage.error('获取会员卡类型列表失败')
  } finally {
    loading.value = false
  }
}

// 添加卡类型
const handleAdd = () => {
  dialogTitle.value = '添加卡类型'
  isEdit.value = false
  dialogVisible.value = true
  // 重置表单
  Object.assign(cardTypeForm, {
    name: '',
    description: '',
    price: 0,
    validityPeriod: 365,
    discount: 1,
    status: 1
  })
}

// 编辑卡类型
const handleEdit = (row: CardType) => {
  dialogTitle.value = '编辑卡类型'
  isEdit.value = true
  dialogVisible.value = true
  currentCardTypeId.value = row.id
  // 填充表单数据
  Object.assign(cardTypeForm, {
    name: row.name,
    description: row.description,
    price: row.price,
    validityPeriod: row.validityPeriod,
    discount: row.discount,
    status: row.status
  })
}

// 删除卡类型
const handleDelete = (row: CardType) => {
  formUtils.handleDeleteConfirm(`卡类型 "${row.name}"`, async () => {
    await cardApi.deleteCardType(row.id)
    getCardTypeList()
  }, {
    successMessage: '删除成功',
    errorMessage: '删除失败'
  })
}

// 保存卡类型信息
const handleSave = async () => {
  if (!cardTypeFormRef.value) return

  await cardTypeFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      // 使用防重复提交保护
      const submitKey = isEdit.value ? `update_card_type_${currentCardTypeId.value}` : 'create_card_type'

      try {
        await preventDuplicateSubmit(submitKey, async () => {
          saveLoading.value = true
          try {
            if (isEdit.value) {
              // 编辑卡类型
              const updateData: UpdateCardTypeRequest = {
                name: cardTypeForm.name,
                description: cardTypeForm.description,
                price: cardTypeForm.price,
                validityPeriod: cardTypeForm.validityPeriod,
                discount: cardTypeForm.discount,
                status: cardTypeForm.status
              }
              await cardApi.updateCardType(currentCardTypeId.value, updateData)
              ElMessage.success('更新成功')
            } else {
              // 添加卡类型
              const createData: CreateCardTypeRequest = {
                name: cardTypeForm.name,
                description: cardTypeForm.description,
                price: cardTypeForm.price,
                validityPeriod: cardTypeForm.validityPeriod,
                discount: cardTypeForm.discount
              }
              await cardApi.createCardType(createData)
              ElMessage.success('添加成功')
            }
            dialogVisible.value = false
            getCardTypeList()
          } catch (error: any) {
            ElMessage.error(isEdit.value ? '更新失败' : '添加失败')
            throw error // 重新抛出错误以确保防重复提交正确处理
          } finally {
            saveLoading.value = false
          }
        })
      } catch (error: any) {
        // 防重复提交保护捕获的错误
        if (error.message === '请勿重复提交') {
          ElMessage.warning('请勿重复提交')
        }
      }
    }
  })
}

// 分页大小改变
const handleSizeChange = (val: number) => {
  pagination.pageSize = val
  pagination.page = 1
  getCardTypeList()
}

// 当前页改变
const handleCurrentChange = (val: number) => {
  pagination.page = val
  getCardTypeList()
}

// 对话框关闭
const handleDialogClose = () => {
  formUtils.resetForm(cardTypeFormRef.value, cardTypeForm, {
    name: '',
    description: '',
    price: 0,
    validityPeriod: 365,
    discount: 1,
    status: 1
  })
}

// 初始化
onMounted(() => {
  getCardTypeList()
})
</script>

<style scoped lang="scss">
.card-type-list {
  .card-type-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .pagination {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
}
</style>
